//
//  String+Ext.swift
//  CocoProject
//
//  Created by Vill on 2023/11/2.
//

import Foundation
import CryptoKit

extension String {
    
    /// 是否为空字符串
    var isEmptyStr: Bool {
        // 扔掉 空格和换行符
        let trimmedStr = self.trimmingCharacters(in: .whitespacesAndNewlines)
        return trimmedStr.isEmpty
    }

    func md5Hash() -> String {
        let inputData = Data(self.utf8)
        let hashedData = Insecure.MD5.hash(data: inputData)
        let hashString = hashedData.map { String(format: "%02hhx", $0) }.joined()
        return hashString
    }
    
    //最近项目需要国家列表添加国旗显示, 国旗没有特别要求, 就想使用系统自带的emoji表情显示
    func emojiFlagForISOCountryCode() -> String {
        let base : UInt32 = 127397
        var s = ""
        for v in self.uppercased().unicodeScalars {
            s.unicodeScalars.append(UnicodeScalar(base + v.value)!)
        }
        return s
    }
    
    func size(width:CGFloat,height:CGFloat = CGFloat(MAXFLOAT),font:UIFont)->CGSize{
        let rect = NSString(string: self).boundingRect(with: CGSize(width: width, height: height), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
        return rect.size
    }
    
    func width(withFont font: UIFont) -> CGFloat {
        let attributes: [NSAttributedString.Key: Any] = [
            .font: font
        ]
        let size = (self as NSString).size(withAttributes: attributes)
        return size.width
    }
    
    func isEmail() -> Bool {
        let emailRegEx = "^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\\.[a-zA-Z0-9]{2,6}$"
        let regExPredicate = NSPredicate(format: "SELF MATCHES %@", emailRegEx)
        var isResult = regExPredicate.evaluate(with: lowercased())
        if isResult {
            isResult = count > 50 ? false : true
        }
        return isResult
    }
    
    // 保存本地设置
    func keySaveToNSDefaults(with value: Any?) {
        let userDefaults = UserDefaults.standard
        userDefaults.setValue(value, forKey: self)
        userDefaults.synchronize()
    }
    
    // 读取本地设置
    func keyGetNSDefaultsKey() -> Any? {
        let userDefaults = UserDefaults.standard
        let result = userDefaults.object(forKey: self)
        return result
    }
    
    /*
     *   添加带图片文本
     */
    func stringWithImage(img:String,bounds:CGRect,isFirst:Bool = false) -> NSAttributedString{
        let markLabelText = isFirst ? " " + self :  self + " "
        let markAttribute = NSMutableAttributedString(string: markLabelText)
        //以上是富文本显示
        let markattch = NSTextAttachment() //定义一个attachment
        markattch.image = UIImage(named: img)//初始化图片
        markattch.bounds = bounds
        let markattchStr = NSAttributedString(attachment: markattch) // 将attachment  加入富文本中
        if isFirst{
            markAttribute.insert(markattchStr, at: 0)// 将markattchStr  加入原有文字的某个位置
        }else{
            markAttribute.append(markattchStr)
        }
        return markAttribute
    }
    
}

